package com.faintlight.service.impl;

import com.faintlight.model.Contact;
import com.faintlight.model.User;
import com.faintlight.repository.ContactRepository;
import com.faintlight.repository.UserRepository;
import com.faintlight.service.ContactService;
import com.faintlight.exception.WarmException;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class ContactServiceImpl implements ContactService {

    private static final Logger logger = LoggerFactory.getLogger(ContactServiceImpl.class);
    private final ContactRepository contactRepository;
    private final UserRepository userRepository;

    @Override
    @Transactional
    public Contact saveContact(Contact contact) {
        logger.info("📌 保存联系人: 姓名={}", contact.getName());

        User user = userRepository.findById(contact.getUser().getId())
                .orElseThrow(() -> new WarmException("用户不存在"));
        contact.setUser(user);

        Contact saved = contactRepository.save(contact);
        logger.info("✅ 联系人保存成功, ID={}", saved.getId());
        return saved;
    }

    @Override
    public List<Contact> getUserContacts(Long userId) {
        logger.info("🔍 查询用户 {} 的联系人", userId);
        List<Contact> contacts = contactRepository.findByUser_Id(userId);
        logger.info("✅ 查询成功, 共 {} 个联系人", contacts.size());
        return contacts;
    }

    @Override
    @Transactional
    public void deleteContact(Long id, Long userId) {
        Contact contact = contactRepository.findById(id)
                .orElseThrow(() -> new WarmException("未找到联系人"));
        if (!contact.getUser().getId().equals(userId)) {
            throw new WarmException("没有权限删除这个联系人");
        }
        contactRepository.delete(contact);
        logger.info("✅ 联系人删除成功, ID={}", id);
    }
}